#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/5/29 11:24
# @Author  : huidong.bai
# @File    : Case.py
# @Software: PyCharm
# @Mail    : MasterBai2018@outlook.com
import pdb
from conf.MongoConfig import INPUT_KEYS, PARAM_KEYS
from conftest import logging


def check_fields(data, fields):
    if data == "NULL":
        return {}
    case_fields = data.split(';')

    _dict = {}
    for field in case_fields:
        if "[" in field and "]" in field:
            value = field[field.index("[") + 1: field.index("]")]
            value = value.split(",")
            _dict[field.split(":")[0]] = value
        else:
            _dict[field.split(":", 1)[0]] = field.split(":", 1)[1]

    for key in _dict.keys():
        # 当断言值为voiceRegion时，不进行处理
        if key == "voiceRegion" or "." in key:
            continue
        if key == "ttsID":
            continue
        elif key not in fields:
            logging.error(f"Attribute {key} is unknown.")
            raise ValueError(f"Attribute {key} is unknown.")
    return _dict


class TestCase:
    def __init__(self) -> None:
        self.inputKeys = None
        self.paramKeys = None
        self.index = None
        self.input = None
        self.param = None
        self.expect = None
        self.reset()

    def reset(self):
        self.index = ""
        self.input = ""
        self.param = ""
        self.expect = {}

    def load_excel_case(self, testcase: dict):
        try:
            self.index = testcase['INDEX']
            self.expect = testcase.get("EXPECT")
            self.input = testcase.get("INPUT")
        except Exception as e:
            logging.error(f"Parse testcase error:{e}, testcase: {testcase}")
            raise Exception(f"Parse testcase error:{e}, testcase: {testcase}")

    def load_case(self, testcase: dict):
        try:
            self.index = testcase['INDEX']
            self.input = check_fields(testcase['INPUT'], INPUT_KEYS)
            self.param = check_fields(testcase['PARAM'], PARAM_KEYS)
            self.expect = testcase['EXPECTS']
        except Exception as e:
            logging.error(f"Parse testcase error:{e}, testcase: {testcase}")
            raise e
